<template>
  <view class="achievements-box">
    <view class="header-box">
      <view class="header" :style="{ paddingTop: useAppData.titleHeight + 3 + 'px' }">
        <view class="back-box" style="left: 0" @tap="gotoBack">
          <image class="back-img" src="../../static/icon-back.png"></image>
        </view>
        <span>我的战绩</span>
      </view>
      <view class="con-box">
        <view class="con-bg">
          <view class="con-info">
            <view class="share-num"> 累计分享 {{state.runData.shareTotal}} </view>
            <view class="info-user">
              <image class="user-avart" :src="state.avartUrl"></image>
              <view class="user-name">
                <p class="name">{{state.runData.type === "share" ? state.shareName : state.userInfo?.customers?.customerName }}</p>
                <p class="time">{{state.runData.shareDate}}</p>
              </view>
            </view>
            <view class="achievements-info">
              <view class="title">今日战绩</view>
              <view class="info-num">
                <view class="num-item">
                  <p class="num">{{state.runData.todayAllMil}}</p>
                  <p class="text">公里数</p>
                </view>
                <view class="num-item">
                  <p class="num">{{state.runData.runAllTime}}</p>
                  <p class="text">时间</p>
                </view>
                <view class="num-item last-item">
                  <p class="num">{{state.runData.runSpeed}}</p>
                  <p class="text">最佳配速</p>
                </view>
              </view>
            </view>
            <view class="participate-box">
              <view class="participate-txt">
                恭喜你成为今日第<text>{{state.runData.ranking}}</text>位全民健康走跑活动的参与者
              </view>
              <image v-if="state.isShareUser" class="share-img" src="../../static/btn-share.png" @tap="onSharePoster"></image>
            </view>
          </view>
          <view class="run-total">
            <p>当前你已累计运动 {{state.runData.runAllMil}}公里</p>
            <p>累计打卡 {{state.runData.clockIn}}</p>
          </view>
          <image class="tip-img" :src="state.runData.randomImg"></image>
          <view class="code-box">
            <view class="code-img">
              <image class="img" src="https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/erweima.png"></image>
              <p class="txt">活动参与入口</p>
            </view>
            <!-- <view class="code-img">
              <image class="img" src="https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/yifengou%402x.png"></image>
              <p class="txt">权益领取入口</p>
            </view> -->
          </view>
        </view>
      </view>
      <mCanvas v-if="state.isShareUser" ref="myCanvasRef" :width="336" :height="626" />
      <view v-if="state.isShareUser" class="btn-share" @tap="onSharePoster">打卡分享</view>
    </view>
  </view>
</template>

<script setup>
import { onLaunch, onLoad, onShow, onHide, onUnload, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
import { reactive, onMounted, ref, getCurrentInstance } from "vue";
import * as API from "../../api/api";
import { getRandomNumImg } from "../../utils/img";
import { getTime, timeConvert } from "../../utils/util";
import { storeToRefs } from "pinia";
import { useRunInfoStore } from "../../store/runInfo";
import { useAppStore } from "../../store/app";
import mCanvas from "../../components/m-canvas";
import { useCommonStore } from "../../store/common";
import { useShareStore } from "../../store/share";
const useShareData = useShareStore()
const useCommonData = useCommonStore()
const useAppData = useAppStore();
const useRunInfoData = useRunInfoStore();
const myCanvasRef = ref();
const { proxy, ctx } = getCurrentInstance()
const state = reactive({
  avartUrl: "https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/avart-wu.png",
  runData: {
    uuid: null,
    type: "user",
    shareDate: proxy.$Moment().format('YYYY-MM-DD HH:mm:ss'),
    shareTotal: 0,
    todayAllMil: 0,
    runAllTime: 0,
    runSpeed: 0,
    runAllMil: 0,
    ranking: 0,
    clockIn: 0,
    randomImg: getRandomNumImg()
  },
  userInfo: null,
  isShareUser: true,
  shareName: null
});

const createPoster = () => {
  let name = state.runData.type === "share" ? state.shareName : state.userInfo?.customers?.customerName
  name = name.length > 7 ? name.substring(0, 7) + "..." : name
  const allStr = "位全民健康走跑活动的参与者"
  let firstStr = ""
  let lastStr = ""
  const ctx = uni.createCanvasContext('myCanvas')
  ctx.font = '20px system-ui'
  const metrics = ctx.measureText(String(state.runData.ranking))
  let rankingWidth = Math.ceil(metrics.width) || '50'
  let lastTextWidth = 336 - rankingWidth - 140
  let lastTextLeft = rankingWidth + 145
  let allTextWidth = 0
  for(let i = 0; i < allStr.length; i++) {
    let itemMetricsWidth = Math.ceil(ctx.measureText(allStr[i]).width)
    allTextWidth += itemMetricsWidth
    firstStr = allStr.substring(0, i)
    if (allTextWidth >= lastTextWidth) {
      lastStr = allStr.substring(i)
      break;
    }
  }
  // 配置项
  const options = [
    // 背景图
    {
      type: "image",
      url: "https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/bg-car.png",
      left: 0,
      top: 0,
      width: 336,
      height: 626,
    },
    // 头像
    {
      type: "image",
      url: state.avartUrl,
      radius: "50%",
      left: 30,
      top: 35,
      width: 54,
      height: 54,
    },
    // 名称
    {
      type: "text",
      // content: "dheuhduhuhuhuhuhuhuhuhuhuhuhuhuhuhuhsuwsugb hehhedbehd ",
      content: name,
      // maxLine: 1,
      color: "#fff",
      fontSize: 16,
      left: 92,
      top: 41,
    },
    // 时间
    {
      type: "text",
      content: state.runData.shareDate,
      color: "#E9F6E3",
      fontSize: 12,
      left: 92,
      top: 66,
    },

    // 累计分享
    {
      type: "text",
      content: `累计分享 ${state.runData.shareTotal}`,
      color: "#1A5540",
      fontSize: 12,
      right: 30,
      top: 29,
    },
    // 个人战绩背景
    {
      type: "block",
      radius: 8,
      isGradient: true,
      startColor: "#E0FFEB",
      endColor: "#E0FFF2",
      left: "center",
      top: 111,
      width: 276,
      height: 117,
    },
    // 今日战绩-box
    {
      // type: 'block',
      // radius: 2,
      // isGradient: true,
      // startColor: "#E0FFEB",
      // endColor: "#E0FFF2",
      // left: 'center',
      // top: 96,
      // width: 72,
      // height: 26
      type: "image",
      url: "https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/jinrizhanji.png",
      radius: 2,
      left: 136,
      top: 125,
      width: 72,
      height: 26,
    },
    // 今日战绩
    {
      type: "text",
      content: "今日战绩",
      color: "#FFFFFF",
      fontSize: 14,
      left: 143,
      top: 130,
    },
    // 公里数值 state.runData.todayAllMil
    {
      type: "text",
      content: state.runData.todayAllMil || "0.00",
      color: "#043D25",
      // fontWeight: "600",
      fontSize: 18,
      width: 100,
      left: 50,
      top: 167,
    },
    // 时间数值
    {
      type: "text",
      content: state.runData.runAllTime,
      color: "#043D25",
      // fontWeight: "600",
      fontSize: 18,
      width: 100,
      left: 131,
      top: 167,
    },
    // 配速数值
    {
      type: "text",
      content: state.runData.runSpeed,
      color: "#043D25",
      // fontWeight: "600",
      fontSize: 18,
      width: 60,
      right: 37,
      top: 167,
    },
    // 公里
    {
      type: "text",
      content: "公里数",
      color: "#1B722B",
      fontSize: 14,
      left: 49,
      top: 195,
    },
    // 时间
    {
      type: "text",
      content: "时间",
      color: "#1B722B",
      fontSize: 14,
      left: 154,
      top: 195,
    },
    // 配速
    {
      type: "text",
      content: "最佳配速",
      color: "#1B722B",
      fontSize: 14,
      right: 40,
      top: 195,
    },
    {
      type: "block",
      radius: 0,
      color: "#9FE9D2",
      left: 113,
      top: 178,
      width: 2,
      height: 25,
    },
    // 短线
    {
      // type: "border",
      // color: "#9FE9D2",
      // width: 2,
      // height: 25,
      // right: 113,
      // top: 150,
      type: "block",
      radius: 0,
      color: "#9FE9D2",
      right: 113,
      top: 178,
      width: 2,
      height: 25,
    },
    // 恭喜你成为今日第
    {
      type: "text",
      content: "恭喜你成为今日第",
      color: "#103D04",
      fontSize: 14,
      left: 30,
      top: 237,
    },
    // 名次
    {
      type: "text",
      content: state.runData.ranking,
      color: "#FE792C",
      fontSize: 20,
      width: rankingWidth,
      left: 145,
      top: 232,
    },
    // 位全民健康走跑活动
    {
      type: "text",
      content: firstStr,
      color: "#103D04",
      fontSize: 14,
      left: lastTextLeft,  // 170
      top: 237,
    },
    // 的参与者
    {
      type: "text",
      content: lastStr,
      color: "#103D04",
      fontSize: 14,
      left: 30,
      top: 258,
    },
    // 累计运动公里
    {
      type: "text",
      content: `当前你已累计运动 ${state.runData.runAllMil}公里`,
      color: "rgba(255, 255, 255, 0.71)",
      fontSize: 13,
      left: 20,
      top: 296,
    },
    // 累计打卡
    {
      type: "text",
      content: `累计打卡 ${state.runData.clockIn}`,
      color: "rgba(255, 255, 255, 0.71)",
      fontSize: 13,
      right: 20,
      top: 296,
    },
    // 随机图
    {
      type: "image",
      url: state.runData.randomImg,
      radius: 0,
      left: "center",
      top: 355,
      width: 304,
      height: 72,
    },
    // 二维码
    {
      type: "image",
      url: "https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/erweima.png",
      radius: 0,
      left: "center",
      bottom: 49,
      width: 82,
      height: 82,
    },
    // 权益
    // {
    //   type: "image",
    //   url: "https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/yifengou%402x.png",
    //   radius: 0,
    //   right: 66,
    //   bottom: 49,
    //   width: 82,
    //   height: 82,
    // },
    // 活动参与入口
    {
      type: "text",
      content: `活动参与入口`,
      color: "#E7E5E9",
      fontSize: 11,
      left: "center",
      bottom: 19,
    },
    // 权益领取入口
    // {
    //   type: "text",
    //   content: `权益领取入口`,
    //   color: "#E7E5E9",
    //   fontSize: 11,
    //   right: 73,
    //   bottom: 19,
    // },
  ];
  // 调用myCanvas的onDraw方法，绘制并保存
  myCanvasRef.value.onDraw(options, (url) => {
    console.log(url);
  }, () => {});
};

const onSharePoster = () => {
  handleCreateShare("poster").then(res => {
    getMileageRecord().then(() => {
      createPoster()
    })
  })
}

const gotoBack = () => {
  let optionsSync = uni.getLaunchOptionsSync()
  if (state.runData.type === 'share' || optionsSync?.scene === 1186 || optionsSync?.scene === 1010) {
    uni.redirectTo({
      url: "/pages/chat/chat"
    })
  } else {
    uni.redirectTo({
      url: "/pages/index/index"
    })
  }
};

 const handleSpeed = (pace) => {
    if (pace > 0) {
      let min = (pace/60).toFixed(2)
      let matchSpeedObj = timeConvert(min)
      return `${matchSpeedObj.min}'${matchSpeedObj.sen}"`
    } else {
      return `0'00"`
    }
  }

const getMileageRecord = () => {
  let params = {
    userId: state.userInfo?.customers?.customerId,
    shareDate: proxy.$Moment().format('YYYY-MM-DD'),
    uuid: state.runData.uuid
  }
  console.log("战绩查询参数", params)
  return new Promise((resolve, reject) => {
    API.getMileageRecordData(params).then(res => {
      if (res.code === 0) {
        console.log("战绩", res.data)
        state.runData = {
          ...state.runData,
          type: state.runData.type,
          shareDate: res.data.sportEndTime,
          shareTotal: res.data.shareTotal || 0,
          todayAllMil: res.data.distance || 0.00,
          runAllTime: getTime(res.data.duration, "hour"),
          runSpeed: handleSpeed(res.data.pace),
          runAllMil: res.data.distanceTotal || 0,
          ranking: res.data.clockInRank || 0,
          clockIn: res.data.clockInTotal || 0
        }
        resolve()
      } else {
        uni.showToast({
          title: res.message || res,
          icon: "none"
        })
      }
    }).catch(err => {
      console.log("查询战绩", err)
    })
  })
};

const handleCreateShare = (shareType) => {
  let params = {
    userId: state.userInfo?.customers?.customerId,
    shareDate: proxy.$Moment().format('YYYY-MM-DD'),
    shareType  // weChat
  }
  console.log("圈", params)
  return new Promise((resolve, reject) => {
    API.createShare(params).then(res => {
      console.log("分享创建成功")
      if (res.code === 0) {
        state.runData.uuid = res.data 
        resolve()
      }
    }).catch(err => {
      console.log("创建分享", err)
    })
  })
}

onLoad((options) => {
  console.log("options", options)
  let optionsSync = uni.getLaunchOptionsSync()
  state.userInfo = uni.getStorageSync("userInfo")
  ? JSON.parse(uni.getStorageSync("userInfo"))
  : null;
  state.runData.type = options?.type || "user"
  if (state.runData.type !== "share") {
    state.isShareUser = true
    state.avartUrl = state.userInfo?.customers?.headUrl || "https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/avart-wu.png"
    handleCreateShare("weChat")
  } else {
    state.runData.uuid = options.uuid
    state.shareName = options.name
    state.avartUrl = options.avartUrl || "https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/avart-wu.png"
    if (options?.shareUserId && state.userInfo?.customers?.customerId === options?.shareUserId) {
      // 分享者本人进入分享页面
      state.isShareUser = true
    } else {
      // 其他人进入分享者页面
      state.isShareUser = false
    }
  }
})

onShow(() => {
  // useCommonData.handleShare()
  useRunInfoData.setProportionShow(0.7);
  useRunInfoData.setInitStatus(true);
  useRunInfoData.setRunType("start")
  useRunInfoData.setRunMileage(0)
  getMileageRecord()
});

onShareAppMessage((res) => {
  console.log("分享给朋友", res, `/examPages/record/achievements?shareUserId=${state.userInfo?.customers?.customerId}&&uuid=${state.runData.uuid}&&type=share&&avartUrl=${state.avartUrl}`)
  return {
    title: "2024廊坊首届全民健康走跑大会火热进行中，奔跑廊坊，体育场等你！",
    path: `/examPages/record/achievements?shareUserId=${state.userInfo?.customers?.customerId}&&name=${state.userInfo?.customers?.customerName}&&uuid=${state.runData.uuid}&&type=share&&avartUrl=${state.avartUrl}`,
    // mpId: 'xxxx', //此处配置微信小程序的AppId
  };
})
onShareTimeline((res) => {
  let path = `/examPages/record/achievements?shareUserId=${state.userInfo?.customers?.customerId}&&name=${state.userInfo?.customers?.customerName}&&uuid=${state.runData.uuid}&&type=share&&avartUrl=${state.avartUrl}`
    console.log("分享到朋友圈=====", path)
  return {
    title: "2024廊坊首届全民健康走跑大会火热进行中，奔跑廊坊，体育场等你！",
    query: `shareUserId=${state.userInfo?.customers?.customerId}&&name=${state.userInfo?.customers?.customerName}&&uuid=${state.runData.uuid}&&type=share&&avartUrl=${state.avartUrl}`,
    // mpId: 'xxxx', //此处配置微信小程序的AppId
  };
})

</script>

<style lang="scss" scoped>
.con-box {
  margin: 34rpx auto;
  overflow: auto;
  .con-bg {
    padding: 0 40rpx;
    box-sizing: border-box;
    margin: 0 auto;
    .share-num {
      font-weight: 500;
      font-size: 24rpx;
      color: #1a5540;
      position: absolute;
      right: 26rpx;
      top: 22rpx;
    }
    .con-info {
      width: 100%;
      height: 545rpx;
      position: relative;
      .info-user {
        display: flex;
        align-items: center;
        margin: 0 0 24rpx 26rpx;
        padding-top: 34rpx;
        .user-avart {
          width: 108rpx;
          height: 108rpx;
          margin-right: 16rpx;
          border-radius: 100%;
        }
        .user-name {
          text-align: left;
          .name {
            width: 250rpx;
            font-weight: 500;
            font-size: 32rpx;
            color: #ffffff;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .time {
            font-size: 24rpx;
            color: #e9f6e3;
          }
        }
      }
      .achievements-info {
        width: 552rpx;
        height: 234rpx;
        background: linear-gradient(180deg, #e0ffeb 0%, #e0fff2 100%);
        border-radius: 16rpx;
        padding: 26rpx 0;
        box-sizing: border-box;
        margin: 0 auto;
        position: relative;
        .title {
          width: 144rpx;
          height: 52rpx;
          background: linear-gradient(147deg, #26c583 0%, #44e28e 33%, #21b474 100%);
          border-radius: 8rpx;
          text-align: center;
          line-height: 52rpx;
          font-size: 28rpx;
          color: #ffffff;
          margin: 0 auto 26rpx;
        }
        .info-num {
          display: flex;
          align-items: center;
          .num-item {
            width: 166rpx;
            padding: 0 25rpx;
            position: relative;
            .num {
              font-weight: 600;
              font-size: 36rpx;
              color: #043d25;
            }
            .text {
              font-size: 28rpx;
              color: #1b722b;
            }
            &::after {
              content: "";
              position: absolute;
              width: 2rpx;
              height: 50rpx;
              background: #9fe9d2;
              top: 50%;
              right: 0;
              transform: translateY(-50%);
            }
          }
          .last-item{
            &::after {
              content: "";
              width: 2rpx;
              height: 50rpx;
              background: #9fe9d2;
              top: 50%;
              right: 1000rpx;
              transform: translateY(-50%);
            }
          }
        }
      }
    }
    .participate-box {
      display: flex;
      justify-content: space-between;
      margin: 18rpx 0 0 26rpx;
      .participate-txt {
        // width: 434rpx;
        font-size: 28rpx;
        color: #103d04;
        text-align: left;
        text {
          font-size: 40rpx;
          color: #fe792c;
        }
      }
      .share-img {
        width: 92rpx;
        height: 92rpx;
        margin-right: 26rpx;
        margin-left: 26rpx;
        flex-shrink: 0;
      }
    }
    .run-total {
      display: flex;
      justify-content: space-between;
      font-size: 26rpx;
      color: rgba(255, 255, 255, 0.71);
      margin-top: 16rpx;
    }
    .tip-img {
      width: 608rpx;
      height: 144rpx;
      margin: 48rpx auto 120rpx;
    }
  }
  .code-box {
    display: flex;
    justify-content: space-around;
    align-items: flex-end;
    font-weight: 500;
    font-size: 22rpx;
    color: #e7e5e9;
    .img {
      width: 164rpx;
      height: 164rpx;
      margin-bottom: 16rpx;
    }
  }
}
.btn-share {
  width: 672rpx;
  height: 104rpx;
  background: #344f6d;
  border-radius: 24rpx;
  font-weight: 500;
  font-size: 32rpx;
  color: #ffffff;
  text-align: center;
  line-height: 104rpx;
  margin: 62rpx auto;
  cursor: pointer;
}
.header-box {
  width: 100vw;
  text-align: center;
  .title {
    font-size: 34rpx;
    color: #000000;
  }
}
.achievements-box {
  width: 100vw;
  min-height: 100vh;
  background-size: 100% 100%;
  padding-bottom: 20rpx;
  box-sizing: border-box;
  background: url("")
    0 0 no-repeat;
}
.con-bg {
  width: 672rpx;
  height: 1168rpx;
  background: url("")
    0 0 no-repeat;
  background-size: 100% 100%;
}
</style>
